﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WAD.WEB.AppCode;
using WAD.Model;
using WAD.DAL;
using System.Data;

namespace WAD.WEB.Client.Ajax
{
    /// <summary>
    /// Advert 的摘要说明
    /// </summary>
    public class Advert : AjaxBase
    {
        public override void AjaxMethodDispatch(String identity)
        {
            switch (identity)
            {
                case "add": this.Add(); break;
                case "update": this.Update(); break;
                case "getcount": this.GetCount(); break;
                case "getdetail": this.GetDetail(); break;
                case "remove": this.Remove(); break;
                case "getlist": this.GetList(); break;
                case "ischange": this.IsChange(); break;
                case "getdetailarticle": this.GetDetailArticle(); break;
            }
        }
        /// <summary>
        /// 添加广告
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void Add()
        {
            IsLogin();
            String title = Parse.String("title");//标题
            String img = Parse.String("img");//图片地址
            String url = HttpUtility.UrlDecode(Parse.String("url"));//广告链接
            int type = Parse.Int("type", 2);//广告显示类型

            //验证
            if (String.IsNullOrEmpty(title) || String.IsNullOrEmpty(img) || String.IsNullOrEmpty(url))
            {
                ParamError();
            }

            MAdvert m = new MAdvert() { title = title, user_id = UserId, img = img, url = url, type = type };
            bool flag = DaoAdvert.Add(m);
            if (flag)
            {
                Success();
            }
            else
            {
                Fail();
            }
        }

        /// <summary>
        /// 修改广告
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void Update()
        {
            IsLogin();

            int id = Parse.Int("id", 0);//广告显示类型
            String title = Parse.String("title");//标题
            String img = Parse.String("img");//图片地址
            String url = HttpUtility.UrlDecode(Parse.String("url"));//广告链接
            int type = Parse.Int("type", 2);//广告显示类型

            MAdvert m = new MAdvert() { id = id, type = type, img = img, title = title, url = url, user_id = UserId };

            //验证
            if (id == 0 || String.IsNullOrEmpty(title) || String.IsNullOrEmpty(img) || String.IsNullOrEmpty(url))
            {
                ParamError();
            }

            if (DaoAdvert.Update(m))
            {
                Success();
            }
            else
            {
                Fail();
            }

        }

        /// <summary>
        /// 返回用户的广告条数
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetCount()
        {
            if (UserId < 1)
                ParamError();
            Success(DaoAdvert.GetCount("advert", "user_id=" + UserId));
        }

        /// <summary>
        /// 获取单条广告信息
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetDetail()
        {
            int id = Parse.Int("id", 0);
            if (id == 0)
            {
                ParamError();
            }

            int type = Parse.Int("type", 0);
            int articleId = Parse.Int("article_id", 0);
            int parentid = Parse.Int("pid", 0);
            String url = Parse.String("url");

            ////判断广告ID，与文章ID是否匹配
            //if (UserId < 1)
            //{
            //    if (!DaoShared.IsExists(id, articleId, 0))
            //        JsonResult(0, "", null);
            //}

            MAdvert m = DaoAdvert.GetEntity(id);
            if (type == 0)
            {
                //如果没有上传type  可能来至其他地方获取的图片详情
                Success(m);
            }

            Success(DaoAdvert.GetDetail(id));
        }

        /// <summary>
        /// 移除广告
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void Remove()
        {
            IsLogin();
            int id = Parse.Int("id", 0);

            String ids = Parse.String("ids");

            //验证
            if (id == 0 || String.IsNullOrEmpty(ids))
            {
                ParamError();
            }

            bool flag = false;

            if (!String.IsNullOrEmpty(ids))
            {
                //删除多条广告
                flag = DaoAdvert.Hides(ids, UserId);
            }
            else
            {
                flag = DaoAdvert.Hide(id, UserId);
            }

            if (flag)
            {
                Success();
            }
            else
            {
                Fail();
            }

        }

        /// <summary>
        /// 获取广告列表
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetList()
        {
            IsLogin();
            int pageIndex = Parse.Int("page_index", 1);//当前页

            PageData pg = DaoAdvert.GetList(pageIndex, 20, UserId);

            if (pg.itemCount == 0)
            {
                DataEmpty();
            }
            else
            {
                Success(pg);
            }
        }

        /// <summary>
        /// 检查用户再次选择广告
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void IsChange()
        {
            IsLogin();
            int advert_id = Parse.Int("advert_id", 0);
            int article_id = Parse.Int("article_id", 0);
            if (advert_id < 1)
                ParamError();

            List<Dictionary<string, object>> list = DaoUserVersion.GetList( UserId, "state,end_date");
            int group = 0;    //免费
            for (int i = 0; i < list.Count; i++)
            {
                object end_date = list[i]["end_date"];
                if (Convert.ToDateTime(end_date).Subtract(DateTime.Now).TotalDays > 0)
                    group = 1;  //未过期
                else
                    group = 2; // 过期
            }

            if (group == 1)
                JsonResult(0, "");
            else if (group == 2)
                JsonResult(500, "账号已过期，续费后才能使用");

            //group==0 判断免费用户是否分享过文章
            MShared model = DaoShared.GetInfoByUserId(UserId);
            if (model != null)
            {
                if (model.advert_id != advert_id || model.article_id != article_id)
                    JsonResult(500, "请升级版本");
            }

            JsonResult(0, "");
        }

        /// <summary>
        /// 获取单条广告,并更新点击数(预览模式)
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetDetailArticle()
        {
            int id = Parse.Int("id", 0);
            int type = Parse.Int("type", 0);    //1 站内文章分享, 2 网页分享
            int articleId = Parse.Int("article_id", 0);
            int parentid = Parse.Int("pid", 0);
            int change = Parse.Int("change", 0);
            int sharedid = Parse.Int("shareid", 0);
            int number = Parse.Int("number", 1);
            String url = HttpUtility.UrlDecode(Parse.String("url"));
            string advertids = Parse.String("advert_ids", "");

            if (id < 1)
            {
                ParamError();
            }
            if (number < 1) number = 1;

            MAdvert ad = DaoAdvert.GetEntity(id);

            //添加广告点击量 (类型不为0  并且文章id和url不同时为空)
            ClientClick.Click(sharedid, 1, id, number);

            if (change == 1 && UserId > 0)
                Edit(ad);     //编辑模式
            else
                Show(ad, articleId, id, sharedid, type, parentid, url); //预览模式
        }

        //获取广告详情(编辑模式)
        void Edit(MAdvert ad)
        {
            Success(ad);
        }

        //获取广告详情(预览模式)
        void Show(MAdvert ad, int articleId, int advert_id, int sharedid, int type, int parentid, string url)
        {
            if (ad == null || ad.user_id.Value < 1)
                JsonResult(1, "广告不存在", null);

            //广告ID与文章ID 或者 广告ID与url 不匹配，则不显示广告
            if (!DaoShared.IsExists(advert_id, articleId, sharedid, url, parentid))
                JsonResult(1, "文章和广告不匹配", null);

            //获取广告发布者的所有版本
            List<Dictionary<string, object>> list = DaoUserVersion.GetList(ad.user_id.Value);

            int group = 0;    //免费
            for (int i = 0; i < list.Count; i++)
            {
                object end_date = list[i]["end_date"];
                if (Convert.ToDateTime(end_date).Subtract(DateTime.Now).TotalDays > 0)
                    group = 1;  //未过期
                else
                    group = 2; // 过期
            }

            if (group == 2)
                JsonResult(1, "版本已过期", null);

            Success(ad);
        }
    }
}